package logic

import (
	"bawei_2112a_shop/common"
	"bawei_2112a_shop/model/mysql"
	"context"
	"errors"
	"gorm.io/gorm"

	"bawei_2112a_shop/order-srv/internal/svc"
	"bawei_2112a_shop/order-srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGenerateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateOrderLogic {
	return &GenerateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GenerateOrderLogic) GenerateOrder(in *order.GenerateOrderRequest) (*order.GenerateOrderResponse, error) {
	// 购物车下单：1、生成订单号 2、查询购物车中的商品信息（根据userId 与 goodsIds可能是一个或多个） 3、计算总价 4、创建订单(扣减真实上哦品库存) 5、清空购物车

	// 1、查询商品是否存在
	goods := mysql.Goods{
		Model: gorm.Model{ID: uint(in.GoodsId)},
	}

	err := goods.GetGoodsDetail()

	if err != nil {
		return nil, errors.New("下单商品异常")
	}

	// 判断商品库存是否充足
	if goods.GoodsStock < int64(in.Count) {
		return nil, errors.New("库存不足")
	}

	amount := float32(in.Count) * goods.GoodsPrice

	o := mysql.Order{
		OrderSn: common.GenerateOrderNo(), // 2、生成订单号
		UserId:  uint(in.UserId),
		Amount:  amount,
		Status:  0,
		Payment: int8(in.PayType),
	}

	err = o.Create()

	// 3、创建订单
	if err != nil {
		return nil, errors.New("创建订单失败")
	}

	OrderItem := mysql.OrderItem{
		OrderSn:    common.GenerateOrderNo(),
		OrderId:    o.ID,
		GoodsId:    uint(in.GoodsId),
		GoodsTitle: goods.GoodsTitle,
		GoodsCover: goods.GoodsCover,
		Count:      int64(in.Count),
		GoodsPrice: goods.GoodsPrice,
		Status:     0,
	}

	err = OrderItem.Create()
	if err != nil {
		return nil, errors.New("创建订单失败")
	}

	// 4、扣减商品真实库存，虚拟库存扣减
	goods.GoodsStock -= int64(in.Count)
	err = goods.UpdateGoodsStock()
	if err != nil {
		return nil, errors.New("更新商品库存失败")
	}
	return &order.GenerateOrderResponse{
		OrderId: int64(o.ID),
	}, nil
}
